<?php
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
require 'db.php'; // 包含数据库连接
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// 检查是否有 JWT
if (!isset($_COOKIE['token'])) {
    echo json_encode(['error' => '用户未登录']);
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode(['error' => '访问被拒绝: ' . $e->getMessage()]);
    exit();
}

$new_username = isset($_POST['new_username']) ? $_POST['new_username'] : null;
$new_password = isset($_POST['hashed_password']) ? $_POST['hashed_password'] : null;
$new_phone = isset($_POST['new_phone']) ? $_POST['new_phone'] : null;

// 准备更新部分
$update_fields = [];
$params = [];
$param_types = ""; // 用于bind_param的类型定义

// 动态生成 SQL 语句和绑定参数
if (!empty($new_username)) {
    $update_fields[] = "username = ?";
    $params[] = $new_username;
    $param_types .= "s"; // 新用户名是字符串类型
}

if (!empty($new_password)) {
    $update_fields[] = "password = ?";
    $params[] = $new_password;
    $param_types .= "s"; // 新密码是字符串类型
}

if (!empty($new_phone)) {
    $update_fields[] = "phone = ?";
    $params[] = $new_phone;
    $param_types .= "s"; // 新手机号是字符串类型
}

// 检查是否有需要更新的字段
if (count($update_fields) > 0) {
    // 获取用户ID
    $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        echo "用户不存在。";
        exit();
    }
    $user = $result->fetch_assoc();
    $stmt->close();

    $params[] = $user_id;
    $param_types .= "i"; // 用户ID是整数类型

    // 准备 SQL 更新语句
    $sql = "UPDATE users SET " . implode(", ", $update_fields) . " WHERE id = ?";
    $stmt = $conn->prepare($sql);
    
    // 动态绑定参数
    $stmt->bind_param($param_types, ...$params);

    // 执行查询
    if ($stmt->execute()) {
        echo "用户资料更新成功。";
    } else {
        echo "更新失败: " . $stmt->error;
    }

    // 关闭查询语句和连接
    $stmt->close();
} else {
    echo "没有要更新的字段。";
}

$conn->close();
?>